package org.example.shop_front_api.controller;

import org.example.shop_front_api.entity.User;
import org.example.shop_front_api.service.UserService;
import org.example.shop_front_api.utils.JsonResult;
import org.example.shop_front_api.utils.JwtUtils;
import org.example.shop_front_api.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public JsonResult login(@RequestBody User user) {
        // 1. 校验用户名和密码
        User dbUser = userService.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (dbUser == null) {
            return JsonResult.failed(400, "用户名或密码错误");
        }
        if (dbUser.getStatus() == 0) {
            return JsonResult.failed(400, "用户已禁用");
        }

        // 2. 生成Token
        String token = jwtUtils.generateToken(dbUser.getUsername());

        // 3. 存入Redis
        stringRedisTemplate.opsForValue().set(
                token,
                token,
                jwtUtils.getExpiration(),
                TimeUnit.MILLISECONDS
        );

        // 4. 登录成功后存入用户上下文
        UserContext.setUser(dbUser);

        // 5. 返回结果
        Map<String, String> result = new HashMap<>();
        result.put("token", "Bearer " + token);
        return JsonResult.success("登录成功", result);
    }
}